<template>
  <div class="global">
    <!-- 用户顶部搜索栏 -->
    <div style="margin-bottom: 10px">
      <el-card shadow="hover">
        <el-form
          :model="message"
          ref="ruleFormRef"
          :rules="rules"
          inline="true"
        >
          <el-form-item>
            <el-button type="primary" @click="change" plain :disabled="isAdmin"
              ><el-icon style="margin-right: 3px"><Plus /></el-icon
              >新增</el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              plain
              v-if="!isAdmin"
              :disabled="batch_delete_flag"
              @click="removeUser"
              ><el-icon style="margin-right: 3px"><Delete /></el-icon
              >删除</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 用户数据表格展示 -->
    <div>
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        stripe
        style="width: 100%"
        height="420"
      >
        <el-table-column type="selection" width="80" />
        <el-table-column prop="name" label="用户名" width="140" />
        <el-table-column prop="deptName" label="部门" width="160" />
        <el-table-column prop="avatar" label="头像" width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-image
                style="border-radius: 100%; width: 50px; height: 50px"
                :src="scope.row.avatar"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="180" />
        <el-table-column prop="message" label="通知" width="300" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
            plain
              type="primary"
              size="small"
              @click="updateUser(scope.row)"
              :disabled="isAdmin"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
            <el-popconfirm
              title="确定要删除吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmEvent(scope.row)"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button plain type="danger" size="small" :disabled="isAdmin"
                  ><el-icon><Delete /></el-icon>
                  删除
                </el-button></template
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 用户数据搜集对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    title="新增通知"
    :center="true"
    :align-center="true"
    width="500px"
    :show-close="false"
  >
    <el-form
      :label-position="right"
      label-width="100px"
      :model="messageForm"
      class="el_form"
      ref="ruleFormRef"
      :rules="rules"
    >
      <el-form-item label="通知内容" prop="message">
        <el-input
          v-model="messageForm.message"
          type="textarea"
          :rows="3"
          placeholder="通知内容，最长150字"
          maxlength="150"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog_footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveUser"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分页部分 -->
  <div class="pagenation">
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="sizes, prev, pager, next"
      :total="total"
      prev-text="第"
      next-text="页"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
  
<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Edit, Delete, Plus } from "@element-plus/icons-vue";
import {
  list,
  save,
  getMessageById,
  removeById,
  update,
} from "@/api/message";
import {useUserStore} from '@/stores/user'
import { useTokenStore } from "@/stores/token";
const TokenStore = useTokenStore();
//解构出tokenStore
const userStore = useUserStore();

///////////////////////////////////////////////////////////////////数据区
const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogFormVisible = ref(false);
const ids = ref([]);
const batch_delete_flag = ref(true);
//模糊查询数据
const message = ref({
  status: "",
});
//保存用户
const messageForm = ref({
  id: null,
  message: "",
});

///////////////////////////////////////////////////////////////////////////方法区
//异步获取用户分页数据
//检测是否是测试账号
const isAdmin = ref(false)
onMounted(async () => {
  //检测是否是测试账号
  isAdmin.value = TokenStore.isAdmin;
  const res = await list(pageNo.value, pageSize.value);
  if (res.code === 200) {
    if (res.data != null) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    }
  }
});

//异步获取用户分页数据
async function initList() {
  await list(pageNo.value, pageSize.value).then((res) => {
    if (res.code === 200) {
      if (res.data != null) {
        tableData.value = res.data.data;
        total.value = res.data.total;
      }
    }
  });
}

//新增用户弹框
function change() {
  dialogFormVisible.value = !dialogFormVisible.value;
}

//表单校验
const ruleFormRef = ref(null);
// 校验规则
const rules = {
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  message: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
};

//新增 / 修改 用户
function saveUser() {
  //表单校验
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (!messageForm.value.id) {
        const user = userStore.user;
        messageForm.value.id = user.id;
        //新增用户
        save(messageForm.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "保存成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      } else {
        //修改用户
        update(messageForm.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "修改成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      }
      dialogFormVisible.value = false;
      cancel();
    }
  });
}

//取消
function cancel() {
  messageForm.value.message = "";
  dialogFormVisible.value = false;
}

//修改用户：回显用户数据
function updateUser(row) {
  getMessageById(row.id).then((res) => {
    if (res.code === 200) {
      messageForm.value = res.data;
      dialogFormVisible.value = true;
    }
  });
}

//批量删除用户
function removeUser() {
  //批量删除
  removeById(ids.value).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  if (ids.value.length > 0) {
    batch_delete_flag.value = false;
  }
  if (ids.value.length === 0) {
    batch_delete_flag.value = true;
  }
}

//pageSize改变时
function handleSizeChange(value) {
  pageSize.value = value;
  initList();
}

//pageNo改变时
function handleCurrentChange(value) {
  pageNo.value = value;
  initList();
}

//单个删除用户
function confirmEvent(row) {
  removeById(row.id).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

//取消删除用户
function cancelEvent() {
  ElMessage({
    showClose: true,
    message: "取消删除！",
    type: "warning",
  });
}
</script>

<style scoped>
.global {
  padding-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
  background-color: #f5f5f5;
}
.pagenation {
  margin-top: 15px;
  margin-left: 500px;
}

.el-input {
  width: 260px;
}

.el_form {
  margin-top: 10px;
  margin-left: 40px;
}

.dialog_footer {
  margin-left: 260px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 100%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
  